package thread;

/**
 * 交替打印ABC
 *
 * 要注意wait和notify的位置
 *
 * 很重要
 */
public class Demo12 {
    static Object locker = new Object();
    static volatile int COUNTER=0;
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            while ((true)) {   //一直打印，改成for循环打印有限次
                synchronized(locker) {
                    while (COUNTER % 3 == 0) {
                        System.out.println("A");
                        COUNTER++;
                        locker.notifyAll();
                    }
                    //如果唤醒之后，不满足条件，要继续等待
                    try {
                        locker.wait();//唤醒
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread t2 = new Thread(()->{
            while ((true)) {
                synchronized(locker) {
                    while (COUNTER % 3 == 1) {
                        System.out.println("B");
                        COUNTER++;
                        locker.notifyAll();
                    }
                    try {
                        locker.wait();//唤醒
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread t3 = new Thread(()->{
            while ((true)) {
                synchronized(locker) {
                    while (COUNTER % 3 == 2) {
                        System.out.println("C");
                        COUNTER++;
                        locker.notifyAll();
                    }
                    try {
                        locker.wait();//唤醒
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }
}
